<?php

Ph::import("library.sm");

class StoresModule extends Module
{
	public $admin = NULL;
	
	public function __config()
	{
		$this->page->template = "control/index.tpl";
		$this->locale->add("control.ini");
		if ( !$this->site->admin_is_auth() )
		{
			$this->site->admin_clear_auth();
			header('Location: /panel/login');
		}
		
		$this->helper = new SMHelper( $this->site );
		$this->admin = new AdminAccess( intval($_SESSION['admin_id']) );
		
		$def = $this->helper->defaults();
		
		if ( !$this->admin->access("stores") ) $this->__stop();
		
	}
	
	
	// Базовая страница магазинов
	public function __default()
	{
		//header("Location: /panel/stores/list");
		
		// Начальная страница Панели управления
		//$this->helper->defaults();
		$this->helper->setMenuActive("stores");
		$this->page->title("_titleStores", true);
		
		$this->page->loadTplToVar("body", "stores/base.tpl");
		$this->page->loadTplToVar("content", "stores/index.tpl");
		
		$this->helper->addBodyTitleButton("/panel/stores/create", "_storesCreate", "blue");
		
		// -----------------------------------------------------------------------------------------------------
		
		
	}
	
	
	// Список магазинов
	public function ListAction()
	{
		
		//$this->helper->defaults();
		$this->helper->setMenuActive("stores");
		$this->helper->setSubmenuActive("stores");
		$this->page->title("_titleStoresList", true);
		
		$this->page->loadTplToVar("body", "stores/base.tpl");
		$this->page->loadTplToVar("content", "stores/list_page.tpl");
		
		$this->helper->addBodyTitleButton("/panel/stores/", "_Back", "white");
		$this->helper->addBodyTitleButton("/panel/stores/create", "_storesCreate", "blue");
		
		// -----------------------------------------------------------------------------------------------------
		
		$this->page->setVar('Locale', $this->locale);
		$list = ORM::for_table('store')->find_array();
		$this->page->setVar("stores_list", $list);
	}
	
	
	// Создание нового магазина
	public function CreateAction()
	{
		//$this->helper->defaults();
		$this->helper->setMenuActive("stores");
		$this->helper->setSubmenuActive("create");
		$this->page->title("_storesCreateIt", true);
		
		$this->locale->addFullPath(_RLOCAL."international.ini");
		
		$this->page->loadTplToVar("body", "stores/base.tpl");
		
		$this->helper->addBodyTitleButton("/panel/stores/", "_Back", "white");
		$this->helper->addBodyTitleButton("/panel/admins/add", "_adminsCreate", "white", "_blank");
		$this->helper->addBodyTitleButton("/panel/stores/import", "_Import", "white");
		
		// -----------------------------------------------------------------------------------------------------
		unset(
				$_SESSION['domain'],
				$_SESSION['title'],
				$_SESSION['langs'],
				$_SESSION['theme'],
				$_SESSION['admin'],
				$_SESSION['activate'],
				$_SESSION['email'],
				$_SESSION['phone'],
				$_SESSION['fax']
			);
		$this->page->loadTplToVar("content", "stores/create_form.tpl");
		$this->page->setVar("BaseSiteDomain", getHost());
		
		// Themes list
		$theme_list = array();
		if ( $dir = opendir(_RTMPL) )
		{
			while( ( $file = readdir( $dir ) ) !== false )
			{
				if ( $file == ".." || $file == "." ) continue;
				if ( is_dir( _RTMPL . $file ) ) $theme_list[] = $file;
			}
		}
		$this->page->setVar("theme_list", $theme_list);
		
		
		// Languages list
		$lang_list = array();
		if ( $dir = opendir(_RLOCAL) )
		{
			$curlang = $this->locale->getLanguage();
			while( ( $file = readdir( $dir ) ) !== false )
			{
				if ( $file == ".." || $file == "." ) continue;
				if ( is_dir( _RLOCAL . $file ) ) $lang_list[$file] = $this->locale->get("_".$file, $curlang);
			}
		}
		$this->page->setVar("lang_list", $lang_list);
		
		
		// Admins
		$adm_list = array();
		$adms = ORM::for_table('admins')->find_array();
		$this->page->setVar("adm_list", $adms);
	}
	
	
	// Подтверждение создания магазина
	public function Create_affirmAction()
	{
		//$this->helper->defaults();
		$this->helper->setMenuActive("stores");
		$this->helper->setSubmenuActive("create");
		$this->page->title("_storesCreateIt", true);
		$this->locale->addFullPath(_RLOCAL."international.ini");
		$this->page->loadTplToVar("body", "stores/base.tpl");
		
		$this->helper->addBodyTitleButton("/panel/stores/create", "_Abort", "white");
		
		// -----------------------------------------------------------------------------------------------------
		$store_create_vars = $this->site->post;
		
		$domain = $this->site->_post('domain');
		$title = $this->site->_post('title');
		$theme = $this->site->_post('theme') ?: "default";
		$admin = $this->site->_post('admin') ? str_replace("admin_", "", $this->site->_post('admin')) : 1;
		$activate = $this->site->_post('activate') ?: "off";
		$email = $this->site->_post('email');
		$phone = $this->site->_post('phone');
		$fax = $this->site->_post('fax') ?: '';
		$langs = array();
		
		unset(
			$store_create_vars['domain'],
			$store_create_vars['title'],
			$store_create_vars['theme'],
			$store_create_vars['admin'],
			$store_create_vars['activate'],
			$store_create_vars['email'],
			$store_create_vars['phone'],
			$store_create_vars['fax']
		);
		
		if ( count($store_create_vars) > 0 )
		{
			foreach($store_create_vars as $key=>$val)
			{
				if ( $val == "on" )
				{
					$langs[] = str_replace("lang_", "", $key);
					unset($store_create_vars[$key]);
				} 
			}
		}
		// -----------------------------------------------------------------------------------------------------
		
		$this->page->loadTplToVar("content", "stores/create_affirm.tpl");
		
		$error = false;
		
		if ( strlen($domain) < 1 )
		{
			$error = new Template("stores/small_error.tpl");
			$error->setLocVar("errorText", "_error_storesDomainLenSmall");
			$this->page->append("stores_errors", $error->processing());
			$error = true;
		}
		
		//if ( preg_match_all("//") )
		
		$check_domain = ORM::for_table('store')->where('domain', $domain)->find_one();
		if ( $check_domain )
		{
			$error = new Template("stores/small_error.tpl");
			$error->setLocVar("errorText", "_error_storesDomainExists");
			$this->page->append("stores_errors", $error->processing());
			$error = true;
		}
		
		if ( strlen( $title ) < 3 )
		{
			$error = new Template("stores/small_error.tpl");
			$error->setLocVar("errorText", "_error_storesSmallTitleLen");
			$this->page->append("stores_errors", $error->processing());
			$error = true;
		}
		
		if ( count($langs) < 1 )
		{
			$error = new Template("stores/small_error.tpl");
			$error->setLocVar("errorText", "_error_storesNoLangs");
			$this->page->append("stores_errors", $error->processing());
			$error = true;
		}
		
		if ( !$phone || $phone == "" )
		{
			$error = new Template("stores/small_error.tpl");
			$error->setLocVar("errorText", "_error_storesPhoneNotExists");
			$this->page->append("stores_errors", $error->processing());
			$error = true;
		}
		
		if ( !$email || $email == "" )
		{
			$error = new Template("stores/small_error.tpl");
			$error->setLocVar("errorText", "_error_storesEmailSupportNotExists");
			$this->page->append("stores_errors", $error->processing());
			$error = true;
		}
		
		if ( $error )
		{
			$this->page->setVar("content", false);
		}
		else
		{
			$this->page->setVar("stores_errors", "");
			$this->page->setVar("content", true);
			$this->page->setVar("setDomain", $domain);
			$this->page->setVar("BaseSiteDomain", getHost());
			$this->page->setVar("setTitle", $title);
			$this->page->setVar("setPhone", $phone);
			$this->page->setVar("setEmail", $email);
			$this->page->setVar("setFax", $fax==''?$this->locale->get("_NoFax"):$fax);
			$languages = array();
			foreach($langs as $key=>$val ) $languages[$key] = $this->locale->get("_".$val, $this->locale->getLanguage());
			$this->page->setVar("setLanguages", implode(", ", $languages));
			$this->page->setVar("setTheme", $theme);
			$admin = ORM::for_table('admins')->where('id', $admin)->find_one();
			$this->page->setVar("setAdmin", $admin?$admin['name']." - ".$admin['email']:$this->locale->get("_adminsNotExists"));
			$this->page->setVar("setActivate", $activate=="on"?true:false);
			
			$_SESSION['domain'] = $domain;
			$_SESSION['title'] = $title;
			$_SESSION['langs'] = $langs;
			$_SESSION['email'] = $email;
			$_SESSION['phone'] = $phone;
			$_SESSION['fax'] = $fax;
			$_SESSION['theme'] = $theme;
			$_SESSION['admin'] = intval($admin['id']);
			$_SESSION['activate'] = $activate;
		}
	}
	
	// Реальное создание магазина
	public function Create_affirmedAction()
	{
		$this->helper->setMenuActive("stores");
		$this->page->title("_storesCreateIt", true);
		
		$this->page->loadTplToVar("body", "stores/base.tpl");
		$this->helper->addBodyTitleButton("/panel/stores/list", "_Back");
		
		// -----------------------------------------------------------------------------------------------------
		if ( isset( $_SESSION['domain'],$_SESSION['title'], $_SESSION['langs'],
					$_SESSION['theme'], $_SESSION['admin'], $_SESSION['activate'],
					$_SESSION['email'], $_SESSION['phone'], $_SESSION['fax'] ) )
		{
			$this->page->loadTplToVar("content", "stores/create_success.tpl");
			$data = ORM::for_table('store')->create();
			$data->domain = $_SESSION['domain'];
			$data->title = iconv("CP1251", "UTF-8", $_SESSION['title']);
			$data->locked = $_SESSION['activate'] == 'on' ? 0 : 1;
			$data->template = $_SESSION['theme'];
			$data->languages = implode(';',$_SESSION['langs']);
			$data->admin_id = intval($_SESSION['admin']);
			$data->phone = $_SESSION['phone'];
			$data->email = $_SESSION['email'];
			$data->fax = $_SESSION['fax'];
			$data->save();
			unset( $_SESSION['domain'],
					$_SESSION['title'],
					$_SESSION['langs'],
					$_SESSION['phone'],
					$_SESSION['email'],
					$_SESSION['fax'],
					$_SESSION['theme'],
					$_SESSION['admin'],
					$_SESSION['activate'] );
		}
		else
		{
			header("Location: /panel/stores/create");
		}
	}
	
	public function OpencontrolpanelAction()
	{
		global $_baseConfig;
		$domain = $this->site->arguments[0];
		$r = ORM::for_table('store')->where('domain', $domain)->find_one();
		
		if ( $r )
		{
			header( "Location: http://".($domain == "www" ? "" :$domain.".").$_baseConfig->get("Site", "domain")."/panel/" );
		}
		else
		{
			
		}
	}
	
	
	// Импортирование настроек нового магазина
	public function ImportAction()
	{
		//$this->helper->defaults();
		$this->helper->setMenuActive("stores");
		$this->helper->setSubmenuActive("import");
		$this->page->title("_titleStores", true);
		
		$this->page->loadTplToVar("body", "stores/base.tpl");
		
		$this->helper->addBodyTitleButton("/panel/stores/", "_Back", "white");
		
		// -----------------------------------------------------------------------------------------------------
		
		
	}
	
	
	// Настраивание магазина
	public function ConfigAction()
	{
		global $_baseConfig;
		
		$this->helper->setMenuActive("stores");
		$this->page->title("_titleStores", true);
		$this->page->loadTplToVar("body", "stores/base.tpl");
		$this->helper->addBodyTitleButton("/panel/stores/list", "_Back", "white");
		$this->locale->addFullPath(_RLOCAL."international.ini");
		
		// -----------------------------------------------------------------------------------------------------
		
		$store_domain = $this->site->arguments[0];
		
		$store = ORM::for_table('store')->where('domain', $store_domain)->find_one();
		
		$this->page->loadTplToVar("content", "stores/edit_form.tpl");
		
		if ( $store )
		{
			$this->page->setVar('stores_no_errors', true);
			$this->page->setVar("setDomain", $store_domain);
			$this->page->setVar("BaseSiteDomain",  $_baseConfig->get("Site", "domain"));
			$this->page->setVar("stores_errors");
			$this->page->setVar("setTitle", $store['title']);
			$this->page->setVar('setEmail', $store['email']);
			$this->page->setVar('setPhone', $store['phone']);
			$this->page->setVar('setFax', $store['fax']);
			
			$this->helper->addBodyTitleButton("/panel/stores/delete/".$store_domain, "_Delete", "red");
			
			// Languages list
			$lang_list = array();
			$langs = explode(';', $store['languages']);
			if ( $dir = opendir(_RLOCAL) )
			{
				
				$curlang = $this->locale->getLanguage();
				while( ( $file = readdir( $dir ) ) !== false )
				{
					if ( $file == ".." || $file == "." || !is_dir( _RLOCAL . $file ) ) continue;
					
					$lang_list[$file] = array(
												$this->locale->get( "_".$file, $curlang ),
												array_search( strval($file), $langs ) === false ? false : true
											);
				}
			}
			$this->page->setVar("lang_list", $lang_list);
			
			// Themes list
			$theme_list = array();
			if ( $dir = opendir(_RTMPL) )
			{
				while( ( $file = readdir( $dir ) ) !== false )
				{
					if ( $file == ".." || $file == "." ) continue;
					if ( is_dir( _RTMPL . $file ) ) $theme_list[] = array($file, $store['template'] == $file ? "yes" : "no");
				}
			}
			$this->page->setVar("theme_list", $theme_list);
			
			// Admins
			$adm_list = array();
			$adms = ORM::for_table('admins')->find_array();
			$this->page->setVar("adm_list", $adms);
			$this->page->setVar("admin_def_id", $store['admin_id']);
			
			$this->page->setVar("activate_after_def", intval($store['locked']) == 0 ? false : true);
		}
		else
		{
			$this->page->setVar('stores_no_errors', false);
			$error = new Template("stores/small_error.tpl");
			$error->setLocVar("errorText", "_error_storesNotExists");
			$this->page->append("stores_errors", $error->processing());
		}
	}
	
	
	// Сохранение изменений
	public function SaveAction()
	{
		$this->helper->setMenuActive("stores");
		$this->page->title("_titleStores", true);
		$this->page->loadTplToVar("body", "stores/base.tpl");
		$this->helper->addBodyTitleButton("/panel/stores/list", "_Abort", "white");
		
		// -----------------------------------------------------------------------------------------------------
		
		$store_create_vars = $this->site->post;
		
		$domain = $this->site->_post('domain');
		$title = $this->site->_post('title');
		$theme = $this->site->_post('theme') ?: "default";
		$admin = $this->site->_post('admin') ? str_replace("admin_", "", $this->site->_post('admin')) : 1;
		$activate = $this->site->_post('activate') ?: "off";
		$email = $this->site->_post('email');
		$phone = $this->site->_post('phone');
		$fax = $this->site->_post('fax') ?: $this->locale->get("_NoFax");
		$langs = array();
		
		unset(
			$store_create_vars['domain'],
			$store_create_vars['title'],
			$store_create_vars['theme'],
			$store_create_vars['admin'],
			$store_create_vars['activate'],
			$store_create_vars['email'],
			$store_create_vars['phone'],
			$store_create_vars['fax']
		);
		
		if ( count($store_create_vars) > 0 )
		{
			foreach($store_create_vars as $key=>$val)
			{
				if ( $val == "on" )
				{
					$langs[] = str_replace("lang_", "", $key);
					unset($store_create_vars[$key]);
				} 
			}
		}
		
		// -----------------------------------------------------------------------------------------------------
		
		$this->page->loadTplToVar("content", "stores/create_affirm.tpl");
		
		$error = false;
		
		if ( strlen($domain) < 1 )
		{
			$error = new Template("stores/small_error.tpl");
			$error->setLocVar("errorText", "_error_storesDomainLenSmall");
			$this->page->append("stores_errors", $error->processing());
			$error = true;
		}
		
		//if ( preg_match_all("//") )
		
		$check_domain = ORM::for_table('store')->where('domain', $domain)->find_one();
		if ( !$check_domain )
		{
			$error = new Template("stores/small_error.tpl");
			$error->setLocVar("errorText", "_error_storesNotExists");
			$this->page->append("stores_errors", $error->processing());
			$error = true;
		}
		
		if ( strlen( $title ) < 3 )
		{
			$error = new Template("stores/small_error.tpl");
			$error->setLocVar("errorText", "_error_storesSmallTitleLen");
			$this->page->append("stores_errors", $error->processing());
			$error = true;
		}
		
		if ( count($langs) < 1 )
		{
			$error = new Template("stores/small_error.tpl");
			$error->setLocVar("errorText", "_error_storesNoLangs");
			$this->page->append("stores_errors", $error->processing());
			$error = true;
		}
		
		if ( !$phone || $phone == "" )
		{
			$error = new Template("stores/small_error.tpl");
			$error->setLocVar("errorText", "_error_storesPhoneNotExists");
			$this->page->append("stores_errors", $error->processing());
			$error = true;
		}
		
		if ( !$email || $email == "" )
		{
			$error = new Template("stores/small_error.tpl");
			$error->setLocVar("errorText", "_error_storesEmailSupportNotExists");
			$this->page->append("stores_errors", $error->processing());
			$error = true;
		}
		
		if ( $error )
		{
			$this->page->setVar("content", false);
		}
		else
		{
			$this->page->setVar("stores_errors", "");
			$this->page->setVar("content", false);
			$languages = array();
			foreach($langs as $key=>$val ) $languages[$key] = $val;
			
			$data = ORM::for_table('store')->where('domain', $domain)->find_one();
			$data->title = $title;
			//qr($activate);
			$data->locked = $activate == "on" ? 1 : 0;
			$data->template = $theme;
			$data->languages = implode(";",$languages);
			$data->phone = $phone;
			$data->fax = $fax;
			$data->email = $email;
			$data->admin_id = $admin;
			$data->save();
			
			header("Location: /panel/stores/list");
		}
	}
	
	
	// Удаление магазина
	public function DeleteAction()
	{
		$this->helper->setMenuActive("stores");
		$this->page->title("_titleStoresRemove", true);
		$this->page->loadTplToVar("body", "stores/base.tpl");
		$this->helper->addBodyTitleButton("/panel/stores/list/", "_Back", "white");
		
		// -----------------------------------------------------------------------------------------------------
		$this->page->loadTplToVar("content", "stores/delete_page.tpl");
		$domain = isset($this->site->arguments[0]) ? $this->site->arguments[0] : '';
		$store = ORM::for_table('store')->where('domain', $domain)->find_one();
		if ( $store )
		{
			$this->page->setVar('content', true);
			$this->page->setVar('stores_errors', false);
			$this->helper->addBodyTitleButton("/panel/stores/remove/".$domain, "_Delete", "red");
			$this->page->setVar("setDomain", $domain);
			$this->page->setVar("setTitle", $store['title']);
			$this->page->setVar('stores_errors');
		}
		else
		{
			$error = new Template("stores/small_error.tpl");
			$error->setLocVar("errorText", "_error_storesNotExists");
			$this->page->append("stores_errors", $error->processing());
			$this->page->setVar('content', false);
		}
		
	}
	
	public function RemoveAction()
	{
		$domain = isset($this->site->arguments[0]) ? $this->site->arguments[0] : '';
		$s = ORM::for_table('store')->where('domain', $domain);
		$s->delete_many();
		header("Location: /panel/stores/list");
	}
}



